package com.xiguaji.tiktok.task.aweme.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.EventBusTemplate;
import com.xiguaji.boot.eventbus.IEventListener;
import com.xiguaji.tiktok.task.aweme.spider.AwemeClient;
import com.xiguaji.tiktok.task.aweme.spider.model.Aweme_list;
import com.xiguaji.tiktok.task.aweme.spider.model.BloggerAwemesResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class SaveBloggerAwemeEventListener implements IEventListener<SaveBloggerAwemeEventListener.SaveBloggerAwemeEvent> {

    @Autowired
    @Lazy
    EventBusTemplate eventBusTemplate;

    @Autowired
    AwemeClient awemeClient;

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(SaveBloggerAwemeEvent event) {
        event.awemeIds.forEach(awemeId -> {
            try {
                run(event, awemeId);
            } catch (Exception ex) {
                log.error("SaveBloggerAweme error. awemeId:" + awemeId);
            }
        });
    }

    private void run(SaveBloggerAwemeEvent event, long awemeId) {
        long max_cursor = 0;
        boolean isHasMore = true;
        List<Aweme_list> awemes = new ArrayList<>();

        try {
            while (isHasMore) {
                BloggerAwemesResponse response = awemeClient.getBloggerAwemes(awemeId, max_cursor, 10);
                if (response == null) break;
                isHasMore = response.isHas_more();
                max_cursor = response.getMax_cursor();
                awemes.addAll(response.getAweme_list());
            }
        } catch (Exception ex) {
            //记录异常，继续进行接下去的操作
            log.error(event.getSource() + " uid:" + awemeId + " count:" + awemes.size(), ex);
        }

        if (awemes.size() > 0) {
            var saveAwemeEvent = new SaveAwemeEventListener.SaveAwemeEvent(event, awemes);
            eventBusTemplate.post(saveAwemeEvent);
        }
    }

    public static class SaveBloggerAwemeEvent extends Event {

        public SaveBloggerAwemeEvent(List<Long> awemeIds) {
            this(null, awemeIds);
        }

        public SaveBloggerAwemeEvent(Event event, List<Long> awemeIds) {
            super(event, "SaveBloggerAweme");
            this.awemeIds = awemeIds;
        }

        private List<Long> awemeIds;
    }
}
